let app = getApp();
import Toast from '../../../components/vant/toast/toast';
import { getLoginCode, smsLogin } from '../../../api/common';
Page({
	data: {
		phone: "",
		isCorrect: false,
		statusHeight: app.globalData.window.statusHeight || 1,
		navheight: app.globalData.window.navheight || 1,
		code: [],
		isGetCode: false,
		codeTime: 60,
		hanleCodeTime: null,
	},
	onLoad(options) {
		this.setData({ phone: options.phone })
		this.getCode()
	},
	changeData(e) {
		let inputValue = e.detail.value;
		this.setData({ code: inputValue })
		this.data.code.length >= 6 && this.login();
	},
	getCode() { //发送验证码
		if (this.data.isGetCode) return false;
		if (!this.data.phone) {
			Toast('手机号码异常，请重新输入')
			return false;
		}
		getLoginCode({ mobile: this.data.phone }).then(()=> {
			wx.showToast({ title:'发送成功', icon: 'success' })
			this.setData({
				isGetCode: true
			}, () => {
				this.setData({
					hanleCodeTime: setInterval(() => {
						let timeNum = this.data.codeTime;
						timeNum--;
						this.setData({ codeTime: timeNum })
						if (this.data.codeTime == 0) {
							this.setData({
								isGetCode: false,
								codeTime: 60
							}, () => {
								clearInterval(this.data.hanleCodeTime)
							})
						}
					}, 1000)
				})
			})
		})
	},
	login() {
        const { unionid, openid, sessionKey, openId } = wx.getStorageSync('wxUserDetails')
        smsLogin({ code: this.data.code, mobile: this.data.phone, openId: openid || openId, unionid, sessionKey }).then(res => {
            wx.setStorageSync('wxToken', res.data.result)

			wx.reLaunch({ url: '/pages/index/index' })
        })
    },
})
